package com.suixun.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.suixun.Constants;
import com.suixun.dao.DevicepurchaseMapper;
import com.suixun.dao.LogincomeMapper;
import com.suixun.dao.LogonlinepayMapper;
import com.suixun.dao.PurchaseDeliveryMapper;
import com.suixun.dao.SchoolinfoMapper;
import com.suixun.dao.StdIotDeviceMapper;
import com.suixun.dao.StdSimidauthMapper;
import com.suixun.dao.devicemanage.DeviceInitServiceDAO;
import com.suixun.dao.onlinepaymanage.OnlinepayManageDAO;
import com.suixun.entity.ChongqingOrderDO;
import com.suixun.entity.Devicepurchase;
import com.suixun.entity.DevicepurchaseExample;
import com.suixun.entity.DiscountOrderDO;
import com.suixun.entity.Factory;
import com.suixun.entity.Logincome;
import com.suixun.entity.LogincomeExample;
import com.suixun.entity.Logonlinepay;
import com.suixun.entity.LogonlinepayExample;
import com.suixun.entity.LogonlinepayExample.Criteria;
import com.suixun.entity.OnlinePayInfo;
import com.suixun.entity.PurchaseDelivery;
import com.suixun.entity.PurchaseDeliveryExample;
import com.suixun.entity.RenewalOrderDO;
import com.suixun.entity.Schoolinfo;
import com.suixun.entity.StdIotDevice;
import com.suixun.entity.StdIotDeviceExample;
import com.suixun.entity.form.OnlinepayForm;
import com.suixun.entity.page.PageModel;
import com.suixun.exception.OpServiceException;
import com.suixun.service.OnlinepayService;
import com.suixun.util.Constant;
import com.suixun.util.DateUtil;
import com.suixun.util.JWTHelper;
import com.suixun.util.StringUtil;
import com.suixun.util.enums.Payment;
import com.suixun.vo.ChongqingOrderVO;
import com.suixun.vo.DeliveryAddrVO;
import com.suixun.vo.DiscountOrderVO;
import com.suixun.vo.OnlinepayVO;
import com.suixun.vo.RenewalOrderVO;
import com.yiji.openapi.YijiService;


/**
 * <p>
 * Title: OnlinepayServiceImpl
 * </p>
 * <p>
 * 功能描述:线上购买业务逻辑类
 * </p>
 * 
 * @author 陈显强
 * @date 2016年12月19日下午3:04:22
 * @version 1.0
 */
@Service("onlinepayService")
public class OnlinepayServiceImpl extends BaseServiceImpl implements OnlinepayService {

	@Autowired
	private OnlinepayManageDAO onlinepayManageDAO;
	@Resource
	private LogonlinepayMapper logonlinepayMapper;
	@Resource
	private LogincomeMapper logincomeMapper;
	@Resource
	private DeviceInitServiceDAO deviceInitServiceDAO;
	@Resource
	private PurchaseDeliveryMapper purchaseDeliveryMapper;
	@Resource
	private DevicepurchaseMapper devicepurchaseMapper;
	@Resource
	private StdIotDeviceMapper stdIotDeviceMapper;
	@Resource
	private StdSimidauthMapper stdSimidauthMapper;
	@Resource
	private SchoolinfoMapper schoolinfoMapper;

	/**
	 * <p>
	 * Title: queryList
	 * </p>
	 * <p>
	 * 功能描述:按条件分页查询产品上线信息
	 * </p>
	 * 
	 * @param onlinepayForm
	 * @return
	 */
	@Override
	public PageModel<OnlinepayVO> queryList(OnlinepayForm onlinepayForm) {
		String peopletel = null, status = null, orderstatus = null;
		PageModel<OnlinepayVO> pageModel = new PageModel<OnlinepayVO>();
		if (onlinepayForm != null) {
			if (StringUtil.isNotEmpty(onlinepayForm.getPeopletel())) {
				peopletel = StringUtil.append(onlinepayForm.getPeopletel());
			}
			if (StringUtil.isNotEmpty(onlinepayForm.getStatus())) {
				status = onlinepayForm.getStatus();
			}
			if (StringUtil.isNotEmpty(onlinepayForm.getOrderstatus())) {
				orderstatus = onlinepayForm.getOrderstatus();
			}
			if (StringUtil.isNotEmpty(onlinepayForm.getPagecount())) {
				pageModel.setPagesize(Integer.parseInt(onlinepayForm.getPagecount()));
			}
			pageModel.getQueryparam().put("orderType", onlinepayForm.getOrderType());
		}
		pageModel.getQueryparam().put("peopletel", peopletel);
		pageModel.getQueryparam().put("status", status);
		pageModel.getQueryparam().put("orderstatus", orderstatus);
		pageModel.getQueryparam().put("starttime", onlinepayForm.getStarttime());
		pageModel.getQueryparam().put("endtime", onlinepayForm.getEndtime());
		pageModel.getQueryparam().put("devicetype", onlinepayForm.getDevicetype());
		Integer totleRows = onlinepayManageDAO.countRows(pageModel);
		pageModel.setTotlepage(totleRows);
		if (onlinepayForm != null) {
			if (StringUtil.isNotEmpty(onlinepayForm.getPagenumber())) {
				pageModel.setCurrentpage(Integer.parseInt(onlinepayForm.getPagenumber()));
			}
		}
		List<OnlinePayInfo> onlinepays = onlinepayManageDAO.queryByPaging(pageModel);
		// 获取未发货数据条数
		pageModel.getQueryparam().put("peopletel", null);
		pageModel.getQueryparam().put("status", 1);
		pageModel.getQueryparam().put("orderstatus", 2);
		int sendRows = onlinepayManageDAO.countRows(pageModel);
		//未发货的数量里面包含已退款的数量,查询已退款数量
		List<Logonlinepay> refundOrdersList = getRefundedList(null);
		int refundOrderRows = 0;
		if (refundOrdersList != null && refundOrdersList.size() > 0) {
			refundOrderRows = refundOrdersList.size();
		} 
		pageModel.setWarningrows(sendRows - refundOrderRows);
		pageModel.setQueryresult(onLinePayInfoToVO(onlinepays));
		return pageModel;
	}

	/**
	 * <p>
	 * Title: listChongqingOrder
	 * </p>
	 * <p>
	 * 功能描述:分页获取重庆订单
	 * </p>
	 * 
	 * @param telephone
	 * @param orderstatus
	 * @param page
	 * @param size
	 * @return
	 * @throws Exception
	 */
	@Override
	public PageModel<ChongqingOrderVO> listChongqingOrder(String telephone, Integer orderstatus, Integer status,
			int page, int size) throws Exception {

		PageModel<ChongqingOrderVO> pageModel = new PageModel<ChongqingOrderVO>();
		pageModel.getQueryparam().put("peopletel", telephone);
		pageModel.getQueryparam().put("orderstatus", orderstatus);
		pageModel.getQueryparam().put("status", status);
		pageModel.setPagesize(size == 0 ? 15 : size);
		Integer totleRows = onlinepayManageDAO.countChongqingOrder(pageModel);
		pageModel.setTotlepage(totleRows);
		pageModel.setCurrentpage(page == 0 ? 1 : page);

		List<ChongqingOrderDO> list = onlinepayManageDAO.listChongqingOrder(pageModel);
		List<ChongqingOrderVO> viewList = new ArrayList<>();
		if (list != null && list.size() > 0) {
			ChongqingOrderVO chongqingOrderVo = null;
			for (ChongqingOrderDO order : list) {
				chongqingOrderVo = new ChongqingOrderVO();
				chongqingOrderVo.setDevicetype(2);
				chongqingOrderVo.setPaystatus("成功");
				chongqingOrderVo.setPaymoney(
						getPayMoney(order.getSmartcardprice(), order.getWhitecard1price(), order.getWhitecard2price(),
								order.getSmartcardnum(), order.getWhitecard1num(), order.getWhitecard2num()));
				chongqingOrderVo.setCreatetime(DateUtil.formatDateToString(order.getCreatetime(), null));
				chongqingOrderVo.setStudentname(order.getStudentname());
				chongqingOrderVo.setClassname(order.getClassname());
				chongqingOrderVo.setSchoolname(order.getSchoolname());
				chongqingOrderVo.setTelephone(order.getTelephone());
				chongqingOrderVo.setMdtid(order.getMdtid());
				chongqingOrderVo.setSendtime(DateUtil.formatDateToString(order.getSendtime(), null));
				chongqingOrderVo.setOrderno(order.getOrderno());
				if (order.getStatus() == null || order.getStatus() == 1) {
					chongqingOrderVo.setStatus(1);
				} else {
					chongqingOrderVo.setStatus(0);
				}
				chongqingOrderVo.setSmspush(order.getSmspush());
				viewList.add(chongqingOrderVo);
			}
		}
		pageModel.setQueryresult(viewList);
		return pageModel;
	}

	/**
	 * 
	 * <p>
	 * Title: queryFactorys
	 * </p>
	 * <p>
	 * 功能描述:查询所有生厂商
	 * </p>
	 * 
	 * @return
	 */
	@Override
	public List<Factory> queryFactorys() {
		return onlinepayManageDAO.queryFactorys();
	}

	/**
	 * 
	 * <p>
	 * Title: validateIMEI
	 * </p>
	 * <p>
	 * 功能描述:验证设备IMEI号
	 * </p>
	 * 
	 * @param onlinepayForm
	 * @return
	 */
	@Override
	public String validateIMEI(OnlinepayForm onlinepayForm) {
		String[] mdtids = null;
		if (StringUtil.isNotEmpty(onlinepayForm.getMdtid())) {
			mdtids = onlinepayForm.getMdtid().split("[\n]");
		}
		for (int i = 0; i < mdtids.length; i++) {
			List<String> isExistList = new LinkedList<String>();
			if (10 == mdtids[i].length()) {
				Map<String, Object> map = new HashMap<>();
				map.put("cardid", mdtids[i]);
				isExistList = onlinepayManageDAO.queryIMEIFromDevicelists(map);
				if (isExistList.size() == 0) {
					return Constant.Device.DEVICE_NOT_IN;
				}
			} else {
				Map<String, Object> map = new HashMap<>();
				map.put("mdtid", mdtids[i]);
				isExistList = onlinepayManageDAO.queryIMEIFromIotDevice(map);
				if (isExistList.size() > 0) {
					continue;
				}
				isExistList = onlinepayManageDAO.queryIMEIFromDevicelists(map);
				if (isExistList.size() == 0) {
					return Constant.Device.DEVICE_NOT_IN;
				}
			}
		}
		return Constant.TRUE;
	}

	/**
	 * 
	 * <p>
	 * Title: sendDevice
	 * </p>
	 * <p>
	 * 功能描述:提交发货信息
	 * </p>
	 * 
	 * @param onlinepayForm
	 * @return
	 * 
	 */
	@Override
	@Transactional
	public int sendDevice(OnlinepayForm onlinepayForm) {
		if (!StringUtil.isNotEmpty(onlinepayForm.getOrderno())
				|| !StringUtil.isNotEmpty(onlinepayForm.getDeliverycompany())
				|| !StringUtil.isNotEmpty(onlinepayForm.getDeliveryno())
				|| !StringUtil.isNotEmpty(onlinepayForm.getMdtid())) {
			return -1;
		}
		//已经发货的不能再次发货
		int isSended = checkSendDevice(onlinepayForm.getOrderno());
		if (isSended == -1) {
			return -2;
		}
		Map<String, Object> map = new HashMap<>();
		map.put("deliverycompany", onlinepayForm.getDeliverycompany());
		map.put("deliveryno", onlinepayForm.getDeliveryno());
		map.put("mdtid", onlinepayForm.getMdtid());
		map.put("orderno", onlinepayForm.getOrderno());
		map.put("operationerid", Integer.parseInt(onlinepayForm.getOperationerid()));
		map.put("orderfrom", 1);
		int result = onlinepayManageDAO.addPurchaseDelivery(map);
		return result;
	}
	/**
	 * <p>Title: checkSendDevice</p>
	 * <p> 功能描述:已经发货的订单不能再发货 </p>
	 * @param orderNo
	 * @return
	 */
	private int checkSendDevice(String orderNo) {
		PurchaseDeliveryExample example = new PurchaseDeliveryExample();
		example.createCriteria().andOrdernoEqualTo(orderNo);
		Integer deliveryCount = purchaseDeliveryMapper.countByExample(example);
		if (deliveryCount != null && deliveryCount > 0) {
			return -1;
		}
		return 1;
	}

	/**
	 * <p>
	 * Title: getDiscountList
	 * </p>
	 * <p>
	 * 功能描述:分页查询促销订单
	 * </p>
	 * 
	 * @param discount
	 * @return
	 * @throws Exception
	 */
	@Override
	public PageModel<DiscountOrderVO> getDiscountList(DiscountOrderVO discount) throws Exception {
		PageModel<DiscountOrderVO> pageModel = new PageModel<DiscountOrderVO>();
		if (StringUtil.isNotEmpty(discount.getStudentname())) {
			pageModel.getQueryparam().put("studentname",
					new StringBuilder().append("%").append(discount.getStudentname()).append("%").toString());
		}
		if (StringUtil.isNotEmpty(discount.getSchoolname())) {
			pageModel.getQueryparam().put("schoolname", discount.getSchoolname());
		}
		if (discount.getSendstatus() != null) {
			pageModel.getQueryparam().put("sendstatus", discount.getSendstatus());
		}
		if (discount.getStatus() != null) {
			pageModel.getQueryparam().put("status", discount.getStatus());
		}
		if (discount.getPagecount() != null) {
			pageModel.setPagesize(discount.getPagecount());
		}
		pageModel.getQueryparam().put("starttime", discount.getStarttime());
		pageModel.getQueryparam().put("endtime", discount.getEndtime());
		pageModel.getQueryparam().put("province", discount.getProvince());
		pageModel.getQueryparam().put("city", discount.getCity());
		pageModel.getQueryparam().put("town", discount.getTown());
		pageModel.getQueryparam().put("orderfrom", 3);//3表示优惠促销
		Integer totleRows = onlinepayManageDAO.countDiscountRows(pageModel);
		pageModel.setTotlepage(totleRows);
		if (discount.getPagenumber() != null) {
			pageModel.setCurrentpage(discount.getPagenumber());
		}
		List<DiscountOrderDO> discountOrderList = onlinepayManageDAO.queryDiscountList(pageModel);
		List<DiscountOrderVO> discountOrderVOList = new ArrayList<>();
		DiscountOrderVO discounOrderVo = null;
		if (discountOrderList.size() > 0) {
			for (DiscountOrderDO discountDO : discountOrderList) {
				discounOrderVo = new DiscountOrderVO();
				discounOrderVo.setPaystatus(Constant.SUCCESS);
				if (discountDO.getSmartcardnum() != null && discountDO.getSmartcardnum() != 0) {
					discounOrderVo.setDevicetype(Constant.Device.SMARTCARD);
				} else if (discountDO.getWhitecard1num() != null && discountDO.getWhitecard1num() != 0) {
					discounOrderVo.setDevicetype(Constant.Device.WHITE_CARD1);
				} else if (discountDO.getWhitecard2num() != null && discountDO.getWhitecard2num() != 0) {
					discounOrderVo.setDevicetype(Constant.Device.WHITE_CARD2);
				}
				discounOrderVo.setPaymoney(getPayMoney(discountDO.getSmartcardprice(), discountDO.getWhitecard1price(),
						discountDO.getWhitecard2price(), discountDO.getSmartcardnum(), discountDO.getWhitecard1num(),
						discountDO.getWhitecard2num()));
				discounOrderVo.setOrderno(discountDO.getOrderno());
				discounOrderVo.setCreatetime(DateUtil.formatDateToString(discountDO.getCreatetime(), null));
				discounOrderVo.setStudentname(discountDO.getStudentname());
				discounOrderVo.setClassname(discountDO.getClassname());
				discounOrderVo.setSchoolname(discountDO.getSchoolname());
				discounOrderVo.setMdtid(discountDO.getMdtid());
				discounOrderVo.setSendtime(DateUtil.formatDateToString(discountDO.getSendtime(), null));
				discounOrderVo.setProvince(discountDO.getProvince());
				discounOrderVo.setCity(discountDO.getCity());
				discounOrderVo.setTown(discountDO.getTown());
				discounOrderVo.setTelephone(discountDO.getTelephone());
				if (discountDO.getStatus() == null || discountDO.getStatus() == 1) {
					discounOrderVo.setStatus(1);
				} else {
					discounOrderVo.setStatus(0);
				}
				if (discountDO.getDevicepackage() != null && "1years".equals(discountDO.getDevicepackage())) {
					discounOrderVo.setDevicepackage(1);
				} else if (discountDO.getDevicepackage() != null && "2years".equals(discountDO.getDevicepackage())) {
					discounOrderVo.setDevicepackage(2);
				}
				discountOrderVOList.add(discounOrderVo);
			}
		}
		pageModel.getQueryparam().put("sendstatus", 0);
		pageModel.getQueryparam().put("status", 1);
		pageModel.getQueryparam().put("studentname", null);
		pageModel.getQueryparam().put("schoolname", null);
		Integer warningrows = onlinepayManageDAO.countDiscountRows(pageModel);
		pageModel.setWarningrows(warningrows);
		pageModel.setQueryresult(discountOrderVOList);
		return pageModel;
	}

	/**
	 * <p>
	 * Title: sendDiscountDevice
	 * </p>
	 * <p>
	 * 功能描述:配送促销订单
	 * </p>
	 * 
	 * @param discount
	 * @return
	 */
	@Override
	public int sendDiscountDevice(DiscountOrderVO discount, long operationerid) {
		Map<String, Object> map = new HashMap<>();
		map.put("operationerid", operationerid);
		if (StringUtil.isEmpty(discount.getSchoolname())) {
			//已经发货的不能再次发货
			int isSended = checkSendDevice(discount.getOrderno());
			if (isSended == -1) {
				return -2;
			}
			String[] orders = discount.getOrderno().split("[|]");
			List<PurchaseDelivery> list = new ArrayList<>();
			PurchaseDelivery delivery = null;
			for (String discountOrderTemp : orders) {
				delivery = new PurchaseDelivery();
				delivery.setOrderno(discountOrderTemp);
				delivery.setMdtid("");
				delivery.setSendtime(DateUtil.formatStringToTime(discount.getSendtime(), "yyyy-MM-dd"));
				delivery.setDeliveryno("");
				delivery.setDeliverycompany("");
				delivery.setOrderfrom(3);
				list.add(delivery);
			}
			map.put("deliverylists", list);
		} else {
			// 查询当前学校的促销订单
			PageModel<DiscountOrderVO> pageModel = new PageModel<DiscountOrderVO>();
			pageModel.getQueryparam().put("schoolname", discount.getSchoolname());
			pageModel.getQueryparam().put("isNotPage", "yes");
			List<DiscountOrderDO> discountOrderList = onlinepayManageDAO.queryDiscountList(pageModel);
			if (discountOrderList.size() == 0) {
				return -1;
			}
			map.put("schoolname", discount.getSchoolname());
			map.put("sendtime", discount.getSendtime());
		}
		onlinepayManageDAO.addPurchaseDelivery(map);
		return 1;
	}

	/**
	 * <p>
	 * Title: getOrderCount
	 * </p>
	 * <p>
	 * 功能描述:获取学校未配送订单数
	 * </p>
	 * 
	 * @param schoolname
	 * @param orderfrom
	 * @return
	 */
	@Override
	public int getOrderCount(String schoolname, Integer orderfrom) {
		PageModel<DiscountOrderVO> pageModel = new PageModel<DiscountOrderVO>();
		pageModel.getQueryparam().put("schoolname", schoolname);
		pageModel.getQueryparam().put("sendstatus", 0);
		pageModel.getQueryparam().put("status", 1);
		pageModel.getQueryparam().put("orderfrom", orderfrom);
		return onlinepayManageDAO.countDiscountRows(pageModel);
	}

	@Override
	public List<DiscountOrderDO> getSchoolNames(Integer orderfrom) {
		return onlinepayManageDAO.getSchoolNames(orderfrom);
	}

	/**
	 * <p>
	 * Title: cancelOrder
	 * </p>
	 * <p>
	 * 功能描述:取消订单
	 * </p>
	 * 
	 * @param discount
	 * @return
	 */
	@Override
	public int cancelOrder(OnlinepayForm onlinepayForm) {
		//判断订单是否已发货
		int isSended = checkSendDevice(onlinepayForm.getOrderno());
		if (isSended == -1) {
			return -2;
		}
		//判断订单是否已经取消
		DevicepurchaseExample purchaseExample = new DevicepurchaseExample();
		purchaseExample.createCriteria().andOrdernoEqualTo(onlinepayForm.getOrderno()).andStatusEqualTo(1);
		purchaseExample.or(purchaseExample.createCriteria().andOrdernoEqualTo(onlinepayForm.getOrderno()).andStatusIsNull());
		List<Devicepurchase> listDevicepurchase = devicepurchaseMapper.selectByExample(purchaseExample);
		if (listDevicepurchase == null || listDevicepurchase.isEmpty()) {
			return -3;
		}
		Map<String, Object> map = new HashMap<>();
		map.put("orderno", onlinepayForm.getOrderno());
		return onlinepayManageDAO.updateOrder(map);
	}

	/**
	 * <p>
	 * Title: exportDiscountList
	 * </p>
	 * <p>
	 * 功能描述:导出促销订单
	 * </p>
	 * 
	 * @param discount
	 * @return
	 * @throws Exception
	 */
	@Override
	public HSSFWorkbook exportDiscountList(DiscountOrderVO discount) throws Exception {
		ArrayList<String> listParm = new ArrayList<String>();
		listParm.add(Constant.Excel.DEVICE_TYPE);
		listParm.add(Constant.Excel.PAY_STATUS);
		listParm.add(Constant.Excel.PAY_MONEY);
		listParm.add(Constant.Excel.PAY_TIME);
		listParm.add(Constant.Excel.OBJECT_NAME);
		listParm.add(Constant.Excel.GRADE);
		listParm.add(Constant.Excel.SCHOOLNAME);
		// listParm.add(Constant.IMEI);
		listParm.add(Constant.Excel.DISCOUNT_SEND_TIME);
		listParm.add(Constant.Excel.STATUS);
		List<List<String>> listValue = new LinkedList<List<String>>();
		if (discount.getPagecount() == null) {
			discount.setPagecount(Integer.parseInt(Constant.Excel.EXPORT_ROWS));
		}
		List<DiscountOrderVO> list = getDiscountList(discount).getQueryresult();
		if (list != null && list.size() > 0) {
			for (DiscountOrderVO discountOrderVO : list) {
				List<String> value = new LinkedList<String>();
				value.add(discountOrderVO.getDevicetype());
				value.add(discountOrderVO.getPaystatus());
				value.add(discountOrderVO.getPaymoney() == null ? null : discountOrderVO.getPaymoney().toString());
				value.add(discountOrderVO.getCreatetime());
				value.add(discountOrderVO.getStudentname());
				value.add(discountOrderVO.getClassname());
				value.add(discountOrderVO.getSchoolname());
				// value.add(discountOrderVO.getMdtid());
				value.add(discountOrderVO.getSendtime());
				if (discountOrderVO.getStatus() == 0) {
					value.add("已取消");
				} else if (discountOrderVO.getStatus() == 1 && discountOrderVO.getSendtime() == null) {
					value.add("未配送");
				} else if (discountOrderVO.getStatus() == 1 && discountOrderVO.getSendtime() != null) {
					value.add("已配送");
				} else {
					value.add(null);
				}
				listValue.add(value);
			}
		}
		return exportList(Constant.Excel.DISCOUNT_EXCEL, listParm, listValue);
	}

	/**
	 * <p>
	 * Title: exportOnlinepayList
	 * </p>
	 * <p>
	 * 功能描述:导出app购买订单
	 * </p>
	 * 
	 * @param onlinepay
	 * @return
	 * @throws Exception
	 */
	@Override
	public HSSFWorkbook exportOnlinepayList(OnlinepayForm onlinepay) throws Exception {
		ArrayList<String> listParm = new ArrayList<String>();
		listParm.add(Constant.Excel.PAY_STATUS);
		listParm.add(Constant.Excel.SMARTCARD_NUM);
		listParm.add(Constant.Excel.WHITE_CARD_NUM1);
		listParm.add(Constant.Excel.WHITE_CARD_NUM2);
		listParm.add(Constant.Excel.PAY_MONEY);
		listParm.add(Constant.Excel.PAY_TIME);
		listParm.add(Constant.Excel.PEOPLE_NAME);
		listParm.add(Constant.Excel.PEOPLE_TEL);
		listParm.add(Constant.Excel.DELIVERY_ADDRESS);
		listParm.add(Constant.Excel.IMEI);
		listParm.add(Constant.Excel.DELIVERY_NUMBER);
		listParm.add(Constant.Excel.SEND_TIME);
		listParm.add(Constant.Excel.STATUS);
		List<List<String>> listValue = new LinkedList<List<String>>();
		if (onlinepay == null) {
			onlinepay = new OnlinepayForm();
		}
		if (StringUtil.isEmpty(onlinepay.getPagecount())) {
			onlinepay.setPagecount(Constant.Excel.EXPORT_ROWS);
		}
		List<OnlinepayVO> pageList = queryList(onlinepay).getQueryresult();
		for (OnlinepayVO onlinepayInfo : pageList) {
			List<String> value = new LinkedList<String>();
			value.add(onlinepayInfo.getPaystatus());
			value.add(onlinepayInfo.getSmartcardnum() == null ? null : String.valueOf(onlinepayInfo.getSmartcardnum()));
			value.add(
					onlinepayInfo.getWhitecard1num() == null ? null : String.valueOf(onlinepayInfo.getWhitecard1num()));
			value.add(
					onlinepayInfo.getWhitecard2num() == null ? null : String.valueOf(onlinepayInfo.getWhitecard2num()));
			value.add(onlinepayInfo.getPaymoney() == null ? null : String.valueOf(onlinepayInfo.getPaymoney()));
			value.add(onlinepayInfo.getPaytime());
			String deliveryaddr = null;
			if (StringUtil.isEmpty(onlinepayInfo.getDeliveryaddr())) {
				deliveryaddr = null;
			} else {
				ObjectMapper mapper = new ObjectMapper();
				DeliveryAddrVO address = null;
				address = mapper.readValue(onlinepayInfo.getDeliveryaddr(), DeliveryAddrVO.class);
				if (address != null && StringUtil.isNotEmpty(address.getName())) {
					onlinepayInfo.setPeoplename(address.getName());
				}
				deliveryaddr = new StringBuffer().append(address.getP()).append(address.getC()).append(address.getT())
						.append(address.getD()).toString();
			}
			value.add(onlinepayInfo.getPeoplename());
			value.add(onlinepayInfo.getPeopletel());
			value.add(deliveryaddr);
			value.add(onlinepayInfo.getMdtid());
			value.add(onlinepayInfo.getDeliveryno());
			value.add(onlinepayInfo.getSendtime());
			if (onlinepayInfo.getStatus() == 0) {
				value.add("已取消");
			} else if (onlinepayInfo.getStatus() == 1 && onlinepayInfo.getDeliveryno() == null) {
				value.add("未发货");
			} else if (onlinepayInfo.getStatus() == 1 && onlinepayInfo.getDeliveryno() != null) {
				value.add("已发货");
			} else {
				value.add(null);
			}
			listValue.add(value);
		}
		return exportList(Constant.Excel.ONLINEPAY_EXCEL, listParm, listValue);
	}

	/**
	 * 退款
	 * <p>
	 * Title: refund
	 * </p>
	 * <p>
	 * 功能描述:
	 * </p>
	 * 
	 * @param onlinepay
	 */
	@Override
	@Transactional
	public String refund(OnlinepayForm onlinepay) {
		checkNull(onlinepay);
		// 获取当前订单信息，确定是否是成功，且是yiji支付
		Logonlinepay logOnlinepay = getLogonlinepayByOrderno(onlinepay.getOrderno());
		if (logOnlinepay == null) {
			return "订单不存在";
		}
		if (!Payment.YIJI.toString().toLowerCase().equals(logOnlinepay.getProvider())) {
			return "只有易极付的订单才能退款";
		}
		if (logOnlinepay.getPaystatus() == null || !logOnlinepay.getPaystatus().contains("SUCCESS")) {
			return "只有支付成功的订单才能退款";
		}
		if (StringUtil.isEmpty(logOnlinepay.getContractno())) {
			return "该订单的流水号为空，不能退款";
		}
		// 校验是否已退款，已退款的订单不能重复退款
		Logonlinepay refundOrder = getRefundOrderByContractNo(logOnlinepay.getContractno());
		if (refundOrder != null && refundOrder.getPaystatus() != null && refundOrder.getPaystatus().contains("SUCCESS")) {
			return "该订单已成功退款";
		}
		Logincome logIncome = getLogincomeByOrderno(onlinepay.getOrderno());
		if (logIncome == null) {
			return "该订单无交易流水信息";
		}
		if (logIncome.getIncome() != null && logIncome.getIncome().compareTo(new BigDecimal(0)) == 0) {
			return "该订单的金额为0，无法退款";
		}
		//校验是否已发货，已发货的不能退款
		int isSend = checkSendDevice(onlinepay.getOrderno());
		if (isSend == -1) {
			return "该订单已发货，不能退款";
		}
		checkIsRefunded(logOnlinepay.getContractno());
		// 退款是一个全新的订单,为退款订单,需要生成一个新的订单号
		String orderno = DigestUtils.md5Hex(UUID.randomUUID().toString());
		String resultCode = "";
		resultCode = YijiService.refund(onlinepay.getOrderno(), orderno, logOnlinepay.getContractno(), "申请退款", logIncome.getIncome());
		// 操作log_onlinepay表
		insertLogOnlinepay(orderno, logOnlinepay.getContractno(), logIncome.getIncome(), logOnlinepay.getDeviceid(),
				logOnlinepay.getUserid(), "yiji", "refund");
		if (resultCode.isEmpty()) {
			return "操作失败";
		}
		return Constant.SUCCESS;
	}
	
	//通过易极付流水号获取对应的退款订单号
	private Logonlinepay getRefundOrderByContractNo(String contractNo) {
		if (contractNo == null) {
			return null;
		}
		LogonlinepayExample logonlinepayExample = new LogonlinepayExample();
		logonlinepayExample.createCriteria().andContractnoEqualTo(contractNo).andServiceEqualTo("refund");
		List<Logonlinepay> logonlinepayList = logonlinepayMapper.selectByExample(logonlinepayExample);
		if (logonlinepayList != null && logonlinepayList.size() > 0) {
			if (logonlinepayList.size() == 1) {
				return logonlinepayList.get(0);
			}else {
				//如果该退款订单有一次成功，则返回成功的退款订单
				for (Logonlinepay logonlinepay : logonlinepayList) {
					if (logonlinepay.getPaystatus().contains("SUCCESS")) {
						return logonlinepay;
					}
				}
				//如果该退款订单一直失败，则获取最后一次退款订单
				return logonlinepayList.get(logonlinepayList.size() - 1);
			}
		}
		return null;
	}

	/**
	 * 
	 * <p>Title: getRefundedList</p>
	 * <p> 功能描述:通过订单号获取指定已退款的订单 ，若orderNo为空，则查询全部已退款订单</p>
	 * @param orderNo
	 * @return
	 */
	private List<Logonlinepay> getRefundedList(String orderNo) {
		LogonlinepayExample logonlinepayExample = new LogonlinepayExample();
		Criteria criteria = logonlinepayExample.createCriteria();
		criteria.andServiceEqualTo("refund").andPaystatusEqualTo("EXECUTE_SUCCESS");
		if (orderNo != null) {
			criteria.andOrdernoEqualTo(orderNo);
		}
		return logonlinepayMapper.selectByExample(logonlinepayExample);
	}
	
	/**
	 * 校验当前订单是否正在申请退款或已退款
	 * <p>
	 * Title: checkIsRefunded
	 * </p>
	 * <p>
	 * 功能描述:
	 * </p>
	 * 
	 * @param tradeNo
	 */
	private void checkIsRefunded(String tradeNo) {
		// 判断是否已退款或在申请退款，若是，则无法继续退款
		LogonlinepayExample logonlinepayExample = new LogonlinepayExample();
		logonlinepayExample.createCriteria().andContractnoEqualTo(tradeNo);
		List<Logonlinepay> logOnlinepayList = logonlinepayMapper.selectByExample(logonlinepayExample);
		if (logOnlinepayList.size() > 0) {
			for (Logonlinepay logonlinepayTemp : logOnlinepayList) {
				// 判断是否已进行退款操作
				if ("refund".equals(logonlinepayTemp.getService())) {
					if (logonlinepayTemp.getPaystatus() == null) {
						throw new OpServiceException("该订单正在等待退款结果");
					} else if ("EXECUTE_SUCCESS".equals(logonlinepayTemp.getPaystatus())) {
						throw new OpServiceException("该订单已退款，无法重复操作");
					}
				}
			}
		}
	}

	private void insertLogOnlinepay(String orderNo, String tradeNo, BigDecimal refundAmount, Integer deviceId,
			Integer userId, String provider, String service) {
		Logonlinepay logonlinepay = new Logonlinepay();
		logonlinepay.setCreatetime(new Date());
		logonlinepay.setOrderno(orderNo);
		logonlinepay.setProvider(provider);
		logonlinepay.setService(service);
		logonlinepay.setUserid(userId);
		logonlinepay.setDeviceid(deviceId);
		logonlinepay.setContractno(tradeNo);
		// 这里暂时保存退款金额，后面会在添加流水里面用到
		logonlinepay.setDescription(refundAmount.toString());
		logonlinepayMapper.insert(logonlinepay);
	}

	/**
	 * 通过订单号获取流水
	 * 
	 * @param orderNo
	 * @return
	 */
	private Logincome getLogincomeByOrderno(String orderNo) {
		LogincomeExample logincomeExample = new LogincomeExample();
		logincomeExample.createCriteria().andOrdernoEqualTo(orderNo);
		List<Logincome> logincomeList = logincomeMapper.selectByExample(logincomeExample);
		if (logincomeList.size() > 0) {
			return logincomeList.get(0);
		}
		return null;
	}

	/**
	 * 通过订单号获取订单
	 * 
	 * @param orderNo
	 * @return
	 */
	private Logonlinepay getLogonlinepayByOrderno(String orderNo) {
		LogonlinepayExample logonlinepayExample = new LogonlinepayExample();
		logonlinepayExample.createCriteria().andOrdernoEqualTo(orderNo);
		List<Logonlinepay> logonlinepays = logonlinepayMapper.selectByExample(logonlinepayExample);
		if (logonlinepays.size() > 0) {
			return logonlinepays.get(0);
		}
		return null;
	}

	private void checkNull(OnlinepayForm onlinepay) {
		if (onlinepay == null || StringUtil.isEmpty(onlinepay.getOrderno())) {
			throw new OpServiceException("订单号不能为空");
		}
	}

	/**
	 * 退款结果
	 * <p>
	 * Title: refunded
	 * </p>
	 * <p>
	 * 功能描述:
	 * </p>
	 * 
	 * @param userid
	 * @param deviceid
	 * @param issuccess
	 * @param orderNo
	 * @param refundAmount
	 * @param payment
	 * @return
	 */
	@Override
	@Transactional
	public void refunded(Integer userid, Integer deviceid, boolean issuccess, String orderNo, String failReason,
			Payment payment) {
		if (issuccess) {
			// 如果已经通知一次则直接跳出
			LogonlinepayExample logonlinepayExample = new LogonlinepayExample();
			logonlinepayExample.createCriteria().andOrdernoEqualTo(orderNo);
			List<Logonlinepay> ents = logonlinepayMapper.selectByExample(logonlinepayExample);
			if (ents != null && ents.size() > 0) {
				if ("EXECUTE_SUCCESS".equals(ents.get(0).getPaystatus())) {
					return;
				}
			}

			BigDecimal refundAmount = new BigDecimal(ents.get(0).getDescription());
			// 修改log_onlinepay表
			Logonlinepay logonlinepay = new Logonlinepay();
			logonlinepay.setPaystatus("EXECUTE_SUCCESS");
			logonlinepayExample = new LogonlinepayExample();
			logonlinepayExample.createCriteria().andOrdernoEqualTo(orderNo);
			logonlinepayMapper.updateByExampleSelective(logonlinepay, logonlinepayExample);
			// 新增log_incomes表
			Logincome logincome = new Logincome();
			logincome.setAddtime(new Date());
			logincome.setIncome(new BigDecimal(new StringBuilder().append("-").append(refundAmount).toString()));
			logincome.setIsbighold(false);
			logincome.setUserid(userid);
			logincome.setDeviceid(deviceid);
			if (payment.equals(Payment.YIJI)) {
				logincome.setChannel("yijifu");
			}
			logincome.setDis("退款");
			logincome.setOrderno(orderNo);
			logincomeMapper.insert(logincome);
			// 如果失败
		} else {
			Logonlinepay logonlinepay = new Logonlinepay();
			logonlinepay.setPaystatus("FAIL");
			logonlinepay.setDescription(failReason);
			LogonlinepayExample logonlinepayExample = new LogonlinepayExample();
			logonlinepayExample.createCriteria().andOrdernoEqualTo(orderNo);
			logonlinepayMapper.updateByExampleSelective(logonlinepay, logonlinepayExample);
		}
	}

	private List<OnlinepayVO> onLinePayInfoToVO(List<OnlinePayInfo> list) {
		List<OnlinepayVO> onlinePayVOs = new LinkedList<>();
		for (OnlinePayInfo onlinepay : list) {
			OnlinepayVO onlinePayVO = new OnlinepayVO();
			onlinePayVO.setMdtid(onlinepay.getMdtid());
			onlinePayVO.setSmartcardnum(
					onlinepay.getSmartcardnum() == null ? null : String.valueOf(onlinepay.getSmartcardnum()));
			onlinePayVO.setSmartcardprice(
					onlinepay.getSmartcardprice() == null ? null : String.valueOf(onlinepay.getSmartcardprice()));
			onlinePayVO.setWhitecard1num(
					onlinepay.getWhitecard1num() == null ? null : String.valueOf(onlinepay.getWhitecard1num()));
			onlinePayVO.setWhitecard1price(
					onlinepay.getWhitecard1price() == null ? null : String.valueOf(onlinepay.getWhitecard1price()));
			onlinePayVO.setWhitecard2num(
					onlinepay.getWhitecard2num() == null ? null : String.valueOf(onlinepay.getWhitecard2num()));
			onlinePayVO.setWhitecard2price(
					onlinepay.getWhitecard2price() == null ? null : String.valueOf(onlinepay.getWhitecard2price()));
			onlinePayVO.setDeliveryno(onlinepay.getDeliveryno());
			onlinePayVO.setDeviceid(onlinepay.getDeviceid() == null ? null : String.valueOf(onlinepay.getDeviceid()));
			onlinePayVO.setPaystatus("成功");
			onlinePayVO.setPaytime(DateUtil.formatDateToString(onlinepay.getCreatetime(), null));
			onlinePayVO.setPeoplename(onlinepay.getPeoplename());
			onlinePayVO.setPeopletel(onlinepay.getPeopletel());
			onlinePayVO.setDeliveryaddr(onlinepay.getDeliveryaddr());
			onlinePayVO.setOrderno(onlinepay.getOrderno());
			onlinePayVO.setPaymoney(String.valueOf(getPayMoney(onlinepay.getSmartcardprice(),
					onlinepay.getWhitecard1price(), onlinepay.getWhitecard2price(), onlinepay.getSmartcardnum(),
					onlinepay.getWhitecard1num(), onlinepay.getWhitecard2num())));
			onlinePayVO.setSendtime(DateUtil.formatDateToString(onlinepay.getSendtime(), null));
			if ("0".equals(String.valueOf(onlinepay.getStatus()))) {
				onlinePayVO.setStatus(0);
			} else {
				onlinePayVO.setStatus(1);
			}
			// 校验当前订单是否存在退款操作，若存在：退款中status=-1,退款失败status=-2,退款成功status=2
			if (onlinepay.getContractno() != null) {
				LogonlinepayExample logonlinepayExample = new LogonlinepayExample();
				logonlinepayExample.createCriteria().andContractnoEqualTo(onlinepay.getContractno());
				List<Logonlinepay> logonlinepayList = logonlinepayMapper.selectByExample(logonlinepayExample);
				if (logonlinepayList.size() > 0) {
					for (Logonlinepay logOnlinepayTemp : logonlinepayList) {
						if (!onlinepay.getOrderno().equals(logOnlinepayTemp.getOrderno())
								&& logOnlinepayTemp.getService() != null
								&& "refund".equals(logOnlinepayTemp.getService())) {
							if (logOnlinepayTemp.getPaystatus() == null) {
								onlinePayVO.setStatus(-1);
								break;
							} else if ("FAIL".equals(logOnlinepayTemp.getPaystatus())) {
								onlinePayVO.setStatus(-2);
								onlinePayVO.setFailReason(logOnlinepayTemp.getDescription());
								break;
							} else if ("EXECUTE_SUCCESS".equals(logOnlinepayTemp.getPaystatus())) {
								onlinePayVO.setStatus(2);
								break;
							}
						}
					}
				}
			}
			onlinePayVOs.add(onlinePayVO);
		}
		return onlinePayVOs;
	}

	private BigDecimal getPayMoney(BigDecimal smartcardprice, BigDecimal whitecard1price, BigDecimal whitecard2price,
			Integer smartcardnum, Integer whitecard1num, Integer whitecard2num) {
		BigDecimal nSmartcardnum = null, nWhitecard1num = null, nWhitecard2num = null;
		smartcardprice = smartcardprice == null ? new BigDecimal(0) : smartcardprice;
		whitecard1price = whitecard1price == null ? new BigDecimal(0) : whitecard1price;
		whitecard2price = whitecard2price == null ? new BigDecimal(0) : whitecard2price;
		nSmartcardnum = smartcardnum == null ? new BigDecimal(0) : new BigDecimal(smartcardnum);
		nWhitecard1num = whitecard1num == null ? new BigDecimal(0) : new BigDecimal(whitecard1num);
		nWhitecard2num = whitecard2num == null ? new BigDecimal(0) : new BigDecimal(whitecard2num);
		BigDecimal smartmoney = smartcardprice.multiply(nSmartcardnum);
		BigDecimal whitecard1money = whitecard1price.multiply(nWhitecard1num);
		BigDecimal whitecard2money = whitecard2price.multiply(nWhitecard2num);
		return smartmoney.add(whitecard1money).add(whitecard2money);
	}

	@Override
	@Transactional
	public void sendChongqingDevice(String orderno, Date sendTime, String mdtid, Integer operationerid) {

		// 1、判断是否已经发货
		
		PurchaseDeliveryExample example = new PurchaseDeliveryExample();
		example.createCriteria().andOrdernoEqualTo(orderno);
		Integer deliveryCount = purchaseDeliveryMapper.countByExample(example);
		if (deliveryCount != null && deliveryCount > 0) {
			throw new RuntimeException("该订单已经发货");
		}

		// 2、判断订单是否已经取消
		DevicepurchaseExample purchaseExample = new DevicepurchaseExample();
		purchaseExample.createCriteria().andOrdernoEqualTo(orderno).andStatusEqualTo(1);
		purchaseExample.or(purchaseExample.createCriteria().andOrdernoEqualTo(orderno).andStatusIsNull());
		List<Devicepurchase> listDevicepurchase = devicepurchaseMapper.selectByExample(purchaseExample);
		if (listDevicepurchase == null || listDevicepurchase.isEmpty()) {
			throw new RuntimeException("订单已取消或者不存在");
		}
		Devicepurchase devicepurchase = listDevicepurchase.get(0);
		if (devicepurchase != null && StringUtil.isBlank(devicepurchase.getTelephone())) {
			throw new RuntimeException("购买手机号为空");
		}

		// 3、判断设备是否入库
		StdIotDeviceExample deviceExample = new StdIotDeviceExample();
		deviceExample.createCriteria().andImeiEqualTo(mdtid);
		List<StdIotDevice> deviceList = stdIotDeviceMapper.selectByExample(deviceExample);
		if (deviceList == null || deviceList.isEmpty()) {
			throw new RuntimeException("设备未入库");
		}

		// 4、判断入库的设备手机号是否为空
		StdIotDevice device = deviceList.get(0);
		if(device.getStatus() != null){
			
			if(device.getStatus() == -1){
				throw new RuntimeException("请先投放设备");
			}
			if(device.getStatus() == 1){
				throw new RuntimeException("该设备已经被绑定");
			}
			
		}
		String simid = device.getSimid();
		if (StringUtil.isBlank(simid)) {
			throw new RuntimeException("设备手机号为空");
		}

		/*// 5、有实名认证，则提醒
		StdSimidauthExample simExample = new StdSimidauthExample();
		simExample.createCriteria().andSimidEqualTo(simid).andStatusEqualTo((byte)3);
		Integer simAuthCount = stdSimidauthMapper.countByExample(simExample);
		if (simAuthCount != null && simAuthCount > 0) {

			throw new RuntimeException("设备手机号冲突");
		}

		StdSimidauth simAuth = new StdSimidauth();
		simAuth.setPeopleid(0);
		simAuth.setSimid(simid);
		Date date = new Date();
		simAuth.setAddtime(date);
		simAuth.setStatus((byte) 3);
		simAuth.setVersion(date);
		simAuth.setPeoplename("");
		simAuth.setIdcardnumber("");
		stdSimidauthMapper.insert(simAuth);

		// 6、拷贝实名认证图片
		try {
			String rootPath = Constants.getMediaSavePath();
			String authPath = rootPath + File.separator + "auth";
			String filePath = authPath + File.separator + devicepurchase.getTelephone();
			String copyPath = authPath + File.separator + simid;
			
			HttpUtil.sendPost(Constants.getApiUrl()+"/operationapp/realNameCheck/copyFolder", "sourceDir="+filePath+"&targetDir="+copyPath, false);
		} catch (Exception e) {
			e.printStackTrace();
		}*/

		PurchaseDelivery purchaseDelivery = new PurchaseDelivery();
		purchaseDelivery.setOrderno(orderno);
		purchaseDelivery.setSendtime(sendTime);
		purchaseDelivery.setDeliverycompany("");
		purchaseDelivery.setDeliveryno("");
		purchaseDelivery.setMdtid(mdtid);
		purchaseDelivery.setOrderfrom(4); // 重庆订单
		purchaseDelivery.setOperationerid(operationerid);
		purchaseDelivery.setStudentname(devicepurchase.getStudentname());
		purchaseDelivery.setClassname(devicepurchase.getClassname());
		Schoolinfo school = schoolinfoMapper.selectByPrimaryKey(devicepurchase.getSchoolid());
		if (school != null) {
			purchaseDelivery.setSchoolname(school.getSchoolname());
		}
		purchaseDeliveryMapper.insert(purchaseDelivery);
	}
	
	@Override
	@Transactional
	public void modifyChongqingDevice(String orderno, Date sendTime, String mdtid) {
		
		PurchaseDeliveryExample example = new PurchaseDeliveryExample();
		example.createCriteria().andOrdernoEqualTo(orderno).andOrderfromEqualTo(4);

		List<PurchaseDelivery> list = purchaseDeliveryMapper.selectByExample(example);
		if (list == null || list.isEmpty()) {
			throw new RuntimeException("该订单未发货或不是重庆订单");
		}

		// 1、判断订单是否已经取消 
		DevicepurchaseExample purchaseExample = new DevicepurchaseExample();
		purchaseExample.createCriteria().andOrdernoEqualTo(orderno).andStatusEqualTo(1);
		purchaseExample.or(purchaseExample.createCriteria().andOrdernoEqualTo(orderno).andStatusIsNull());
		List<Devicepurchase> listDevicepurchase = devicepurchaseMapper.selectByExample(purchaseExample);
		if (listDevicepurchase == null || listDevicepurchase.isEmpty()) {
			throw new RuntimeException("订单已取消或者不存在");
		}
		Devicepurchase devicepurchase = listDevicepurchase.get(0);
		if (devicepurchase != null && StringUtil.isBlank(devicepurchase.getTelephone())) {
			throw new RuntimeException("购买手机号为空");
		}
		
		PurchaseDelivery purchaseDelivery = list.get(0);
		//如果修改设备id不为空，并且不是之前的设备id，则进行实名认证
		if(StringUtil.isNotBlank(mdtid) && !mdtid.equals(purchaseDelivery.getMdtid())){
			
			// 2、判断设备是否入库
			StdIotDeviceExample deviceExample = new StdIotDeviceExample();
			deviceExample.createCriteria().andImeiEqualTo(mdtid);
			List<StdIotDevice> deviceList = stdIotDeviceMapper.selectByExample(deviceExample);
			if (deviceList == null || deviceList.isEmpty()) {
				throw new RuntimeException("设备未入库");
			}

			// 3、判断入库的设备手机号是否为空
			StdIotDevice device = deviceList.get(0);
			String simid = device.getSimid();
			if (StringUtil.isBlank(simid)) {
				throw new RuntimeException("设备手机号为空");
			}
			
			/*// 4、有实名认证，则提醒
			StdSimidauthExample simExample = new StdSimidauthExample();
			simExample.createCriteria().andSimidEqualTo(simid).andStatusEqualTo((byte)3);
			Integer simAuthCount = stdSimidauthMapper.countByExample(simExample);
			if (simAuthCount != null && simAuthCount > 0) {

				throw new RuntimeException("设备手机号冲突");
			}

			StdSimidauth simAuth = new StdSimidauth();
			simAuth.setPeopleid(0);
			simAuth.setSimid(simid);
			Date date = new Date();
			simAuth.setAddtime(date);
			simAuth.setStatus((byte) 3);
			simAuth.setVersion(date);
			simAuth.setPeoplename("");
			simAuth.setIdcardnumber("");
			stdSimidauthMapper.insert(simAuth);
			purchaseDelivery.setMdtid(mdtid);
			// 6、拷贝实名认证图片
			try {
				String rootPath = Constants.getMediaSavePath();
				String authPath = rootPath + File.separator + "auth";
				String filePath = authPath + File.separator + devicepurchase.getTelephone();
				String copyPath = authPath + File.separator + simid;
				HttpUtil.sendPost(Constants.getApiUrl()+"/operationapp/realNameCheck/copyFolder", "sourceDir="+filePath+"&targetDir="+copyPath, false);
			} catch (Exception e) {
				e.printStackTrace();
			}*/
			
		}
		
		if(sendTime != null){
			purchaseDelivery.setSendtime(sendTime);
		}
		
		purchaseDeliveryMapper.updateByPrimaryKey(purchaseDelivery);

	}

	/**
	 * <p>Title: getIdCardByPeopleTel</p>
	 * <p> 功能描述:获取身份证图片 </p>
	 * @param peopletel
	 * @return
	 * @throws Exception
	 */
	@Override
	public String getIdCardByPeopleTel(String peopletel, String cardProperty) throws Exception {
		//生成token
		JWTHelper jeHelper = new JWTHelper();
		String token = jeHelper.createJWT("1", "suixun","testname testpassword",0l,"operation");
		return Constants.getApiUrl() + "/media/auth/" + token+"/" + peopletel+"/"+cardProperty;
	}
	
	/**
	 * <p>Title: getNotSendCounts</p>
	 * <p> 功能描述:获取未发货数量 </p>
	 * @return
	 */
	@Override
	public Map<String,Object> getNotSendCounts() {
		PageModel<?> pageModel = new PageModel<>();
		//获取app购买订单未发货数量
		pageModel.getQueryparam().put("status", 1);
		pageModel.getQueryparam().put("orderstatus", 2);
		int appNotSendCounts = onlinepayManageDAO.countRows(pageModel);
		
		//未发货的数量里面包含已退款的数量,获取已退款数量
		List<Logonlinepay> refundOrdersList = getRefundedList(null);
		int refundOrderCounts = 0;
		if (refundOrdersList != null && refundOrdersList.size() > 0) {
			refundOrderCounts = refundOrdersList.size();
		}
		
		appNotSendCounts = appNotSendCounts - refundOrderCounts;
		
		//获取限时优惠订单未发货数量
		pageModel = new PageModel<>();
		pageModel.getQueryparam().put("sendstatus", 0);
		pageModel.getQueryparam().put("status", 1);
		pageModel.getQueryparam().put("orderfrom", 3);
		int discountNotSendCounts = onlinepayManageDAO.countDiscountRows(pageModel);
		
		//获取新优惠订单未发货数量
		pageModel = new PageModel<>();
		pageModel.getQueryparam().put("sendstatus", 0);
		pageModel.getQueryparam().put("status", 1);
		pageModel.getQueryparam().put("orderfrom", 5);
		int newDiscountNotSendCounts = onlinepayManageDAO.countDiscountRows(pageModel);
		
		//获取重庆订单未发货数量
		pageModel = new PageModel<>();
		pageModel.getQueryparam().put("status", 1);
		pageModel.getQueryparam().put("orderstatus", 2);
		int chongqingNotSendCounts = onlinepayManageDAO.countChongqingOrder(pageModel);

        //获取和教育订单未发货数量
        pageModel = new PageModel<>();
        pageModel.getQueryparam().put("status", 1);
        pageModel.getQueryparam().put("orderstatus", 2);
        pageModel.getQueryparam().put("orderType", 1);
        int hejiaoyuNotSendCounts = onlinepayManageDAO.countRows(pageModel);
		
		Map<String,Object> map = new HashMap<>();
		map.put("appNotSendCounts", appNotSendCounts);
		map.put("discountNotSendCounts", discountNotSendCounts);
		map.put("chongqingNotSendCounts", chongqingNotSendCounts);
		map.put("newDiscountNotSendCounts", newDiscountNotSendCounts);
        map.put("hejiaoyuNotSendCounts", hejiaoyuNotSendCounts);
		return map;
	}

	/**
	 * <p>Title: listRenewalOrders</p>
	 * <p> 功能描述:分页查询续费订单 </p>
	 * @param renewalVo
	 * @return
	 */
	@Override
	public PageModel<RenewalOrderVO> listRenewalOrders(String peopletel, String mdtid, int page, int size, Integer orderType) {
		PageModel<RenewalOrderVO> pageModel = new PageModel<>();
		pageModel.getQueryparam().put("peopletel", peopletel);
		pageModel.getQueryparam().put("mdtid", mdtid);
		pageModel.getQueryparam().put("orderType", orderType);
		pageModel.setPagesize(size == 0 ? 15 : size);
		Integer totleRows = onlinepayManageDAO.getRenewalOrderRows(pageModel);
		pageModel.setTotlepage(totleRows);
		pageModel.setCurrentpage(page == 0 ? 1 : page);
		List<RenewalOrderDO> list = onlinepayManageDAO.getRenewalOrderList(pageModel);
		List<RenewalOrderVO> viewList = new ArrayList<>();
		if (list != null && list.size() > 0) {
			String description = null;
			String renewalPackage = null;
			RenewalOrderVO renewalOrderVo = null;
			Logonlinepay logonlinepay = null;
			Logonlinepay refundOrder = null;
			for (RenewalOrderDO renewalOrerDo : list) {
				Integer status = 1;//默认为续费状态
				renewalOrderVo = new RenewalOrderVO();
				renewalOrderVo.setMdtid(renewalOrerDo.getMdtid());
				renewalOrderVo.setOrderno(renewalOrerDo.getOrderno());
				renewalOrderVo.setRenewalaccount(renewalOrerDo.getPeopletel());
				renewalOrderVo.setRenewalmoney(renewalOrerDo.getIncome());
				description = renewalOrerDo.getDescription();
				if (description != null && description.length() > 1) {
					renewalPackage = String.format("%s年", description.substring(0,1));
				}
				renewalOrderVo.setRenewalPackage(renewalPackage);
				renewalOrderVo.setRenewaltime(DateUtil.formatDateToString(renewalOrerDo.getCreatetime(), null));
				logonlinepay = getLogonlinepayByOrderno(renewalOrerDo.getOrderno());
				if (logonlinepay != null) {
					refundOrder = getRefundOrderByContractNo(logonlinepay.getContractno());
				}
				if (refundOrder != null) {
					if (refundOrder.getPaystatus() == null) {
						//退款中
						status = 2;
					}else if (refundOrder.getPaystatus().contains("SUCCESS")) {
						//退款成功
						status = 3;
					}else if (refundOrder.getPaystatus().contains("FAIL")) {
						//退款失败
						status = -1;
					}
				}
				renewalOrderVo.setStatus(status);
				viewList.add(renewalOrderVo);
			}
		}
		pageModel.setQueryresult(viewList);
		return pageModel;
	}
	
	@Override
	public RenewalOrderVO getLastRenewalOrder(String peopletel, String mdtid) {
		PageModel<RenewalOrderVO> pageModel = new PageModel<>();
		pageModel.getQueryparam().put("mdtid", mdtid);
		pageModel.getQueryparam().put("peopletel", peopletel);
		pageModel.setStartposition(0);
		pageModel.setPagesize(1);
		List<RenewalOrderDO>  renewalList = onlinepayManageDAO.getRenewalOrderList(pageModel);
		if (CollectionUtils.isEmpty(renewalList)) {
			return null;
		}
		RenewalOrderVO renewalOrderVo = new RenewalOrderVO();
		RenewalOrderDO renewalOrerDo = renewalList.get(0);
		renewalOrderVo.setMdtid(renewalOrerDo.getMdtid());
		renewalOrderVo.setOrderno(renewalOrerDo.getOrderno());
		renewalOrderVo.setRenewalaccount(renewalOrerDo.getPeopletel());
		renewalOrderVo.setRenewalmoney(renewalOrerDo.getIncome());
		String description = renewalOrerDo.getDescription();
		String renewalPackage = null;
		Logonlinepay logonlinepay = null;
		Logonlinepay refundOrder = null;
		if (description != null && description.length() > 1) {
			renewalPackage = String.format("%s年", description.substring(0,1));
		}
		renewalOrderVo.setRenewalPackage(renewalPackage);
		renewalOrderVo.setRenewaltime(DateUtil.formatDateToString(renewalOrerDo.getCreatetime(), null));
		logonlinepay = getLogonlinepayByOrderno(renewalOrerDo.getOrderno());
		if (logonlinepay != null) {
			refundOrder = getRefundOrderByContractNo(logonlinepay.getContractno());
		}
		Integer status = 1;
		if (refundOrder != null) {
			if (refundOrder.getPaystatus() == null) {
				//退款中
				status = 2;
			}else if (refundOrder.getPaystatus().contains("SUCCESS")) {
				//退款成功
				status = 3;
			}else if (refundOrder.getPaystatus().contains("FAIL")) {
				//退款失败
				status = -1;
			}
		}
		renewalOrderVo.setStatus(status);
		return renewalOrderVo;
	}
	
	
	
	
	@Override
	public PageModel<DiscountOrderVO> getNewDiscountPage(DiscountOrderVO discount) {
		PageModel<DiscountOrderVO> pageModel = new PageModel<DiscountOrderVO>();
		if (StringUtil.isNotEmpty(discount.getStudentname())) {
			pageModel.getQueryparam().put("studentname",
					new StringBuilder().append("%").append(discount.getStudentname()).append("%").toString());
		}
		if (StringUtil.isNotEmpty(discount.getSchoolname())) {
			pageModel.getQueryparam().put("schoolname", discount.getSchoolname());
		}
		if (discount.getSendstatus() != null) {
			pageModel.getQueryparam().put("sendstatus", discount.getSendstatus());
		}
		if (discount.getStatus() != null) {
			pageModel.getQueryparam().put("status", discount.getStatus());
		}
		if (discount.getPagecount() != null) {
			pageModel.setPagesize(discount.getPagecount());
		}
		pageModel.getQueryparam().put("starttime", discount.getStarttime());
		pageModel.getQueryparam().put("endtime", discount.getEndtime());
		pageModel.getQueryparam().put("province", discount.getProvince());
		pageModel.getQueryparam().put("city", discount.getCity());
		pageModel.getQueryparam().put("town", discount.getTown());
		pageModel.getQueryparam().put("orderfrom", 5);//5表示新优惠促销
		Integer totleRows = onlinepayManageDAO.countDiscountRows(pageModel);
		pageModel.setTotlepage(totleRows);
		if (discount.getPagenumber() != null) {
			pageModel.setCurrentpage(discount.getPagenumber());
		}
		List<DiscountOrderDO> discountOrderList = onlinepayManageDAO.queryDiscountList(pageModel);
		List<DiscountOrderVO> discountOrderVOList = new ArrayList<>();
		DiscountOrderVO discounOrderVo = null;
		if (discountOrderList.size() > 0) {
			for (DiscountOrderDO discountDO : discountOrderList) {
				discounOrderVo = new DiscountOrderVO();
				discounOrderVo.setPaystatus(Constant.SUCCESS);
				discounOrderVo.setAddress(discountDO.getAddress());//新加收货地址
				if (discountDO.getSmartcardnum() != null && discountDO.getSmartcardnum() != 0) {
					discounOrderVo.setDevicetype(Constant.Device.SMARTCARD);
				} else if (discountDO.getWhitecard1num() != null && discountDO.getWhitecard1num() != 0) {
					discounOrderVo.setDevicetype(Constant.Device.WHITE_CARD1);
				} else if (discountDO.getWhitecard2num() != null && discountDO.getWhitecard2num() != 0) {
					discounOrderVo.setDevicetype(Constant.Device.WHITE_CARD2);
				}
				discounOrderVo.setPaymoney(getPayMoney(discountDO.getSmartcardprice(), discountDO.getWhitecard1price(),
						discountDO.getWhitecard2price(), discountDO.getSmartcardnum(), discountDO.getWhitecard1num(),
						discountDO.getWhitecard2num()));
				discounOrderVo.setOrderno(discountDO.getOrderno());
				discounOrderVo.setCreatetime(DateUtil.formatDateToString(discountDO.getCreatetime(), null));
				discounOrderVo.setStudentname(discountDO.getStudentname());
				discounOrderVo.setClassname(discountDO.getClassname());
				discounOrderVo.setSchoolname(discountDO.getSchoolname());
				discounOrderVo.setMdtid(discountDO.getMdtid());
				discounOrderVo.setSendtime(DateUtil.formatDateToString(discountDO.getSendtime(), null));
				discounOrderVo.setProvince(discountDO.getProvince());
				discounOrderVo.setCity(discountDO.getCity());
				discounOrderVo.setTown(discountDO.getTown());
				discounOrderVo.setTelephone(discountDO.getTelephone());
				if (discountDO.getStatus() == null || discountDO.getStatus() == 1) {
					discounOrderVo.setStatus(1);
				} else {
					discounOrderVo.setStatus(0);
				}
				if (discountDO.getDevicepackage() != null && "1years".equals(discountDO.getDevicepackage())) {
					discounOrderVo.setDevicepackage(1);
				} else if (discountDO.getDevicepackage() != null && "2years".equals(discountDO.getDevicepackage())) {
					discounOrderVo.setDevicepackage(2);
				}
				discountOrderVOList.add(discounOrderVo);
			}
		}
		pageModel.getQueryparam().put("sendstatus", 0);
		pageModel.getQueryparam().put("status", 1);
		pageModel.getQueryparam().put("studentname", null);
		pageModel.getQueryparam().put("schoolname", null);
		Integer warningrows = onlinepayManageDAO.countDiscountRows(pageModel);
		pageModel.setWarningrows(warningrows);
		pageModel.setQueryresult(discountOrderVOList);
		return pageModel;
	}
	
	@Override
	public int sendNewDiscountDevice(DiscountOrderVO discount, long operationerid) {
		Map<String, Object> map = new HashMap<>();
		map.put("operationerid", operationerid);
		if (StringUtil.isEmpty(discount.getSchoolname())) {
			//已经发货的不能再次发货
			int isSended = checkSendDevice(discount.getOrderno());
			if (isSended == -1) {
				return -2;
			}
			String[] orders = discount.getOrderno().split("[|]");
			List<PurchaseDelivery> list = new ArrayList<>();
			PurchaseDelivery delivery = null;
			for (String discountOrderTemp : orders) {
				delivery = new PurchaseDelivery();
				delivery.setOrderno(discountOrderTemp);
				delivery.setMdtid("");
				delivery.setSendtime(DateUtil.formatStringToTime(discount.getSendtime(), "yyyy-MM-dd"));
				delivery.setDeliveryno("");
				delivery.setDeliverycompany("");
				delivery.setOrderfrom(5);
				list.add(delivery);
			}
			map.put("deliverylists", list);
		} else {
			// 查询当前学校的促销订单
			PageModel<DiscountOrderVO> pageModel = new PageModel<DiscountOrderVO>();
			pageModel.getQueryparam().put("schoolname", discount.getSchoolname());
			pageModel.getQueryparam().put("isNotPage", "yes");
			pageModel.getQueryparam().put("orderfrom", 5);
			List<DiscountOrderDO> discountOrderList = onlinepayManageDAO.queryDiscountList(pageModel);
			if (discountOrderList.size() == 0) {
				return -1;
			}
			map.put("schoolname", discount.getSchoolname());
			map.put("sendtime", discount.getSendtime());
		}
		onlinepayManageDAO.addNewPurchaseDelivery(map);
		return 1;
	}
}
